package person.learn.conf.commandline;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import person.learn.entity.Goods;
import person.learn.entity.User;
import person.learn.service.GoodsService;
import person.learn.service.UserService;

/**
 * Created by barton on 16-1-31.
 * 1.如果你想获取原始的命令行参数，或一旦SpringApplication启动，你需要运行一些特定的代码，
 * 你可以实现CommandLineRunner接口。在所有实现该接口的Spring
 * beans上将调用run(String… args)方法。
 * 2.看控制台最后几行的日志输出
 * 3.使用@Profile("dev")注解只有profile环境等于dev时才执行。java -jar xx.jar --spring.profiles.active=dev
 */
@Component
//@Profile("dev")
public class CommandLineConfig implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(CommandLineConfig.class);

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Spring Application 启动后 执行 一些特定的代码或者获取原始的命令行参数");
        logger.info("执行输出 群主是SB");

        StringBuffer sb = new StringBuffer("获取命令行参数 ");
        for (String arg : args) {
            sb.append(arg).append(" ");
        }
        logger.info(sb.toString());

        // 执行sql，插入goods表的测试数据
        Goods g1 = new Goods();
        g1.setName("abc");
        g1.setCount(10);
        g1.setDescription("g1descrition");

        goodsService.save(g1);

        Goods g2 = new Goods();
        g2.setName("abcdef");
        g2.setCount(20);
        g2.setDescription("g2descrition");

        goodsService.save(g2);

        // 追加一个可登陆用户
        User user = new User();
        user.setId("1");
        user.setUserName("admin");
        user.setPassword("123456");

        if (null == this.userService.findByUserName("admin")) {
            this.userService.add(user);
        }
    }
}
